from PIL import Image
import os

# 设置源文件夹和目标文件夹
source_folder = os.getcwd()  # 当前目录  # 需要修改为源文件夹的路径
destination_folder = os.getcwd()  # 当前目录  # 需要修改为目标文件夹的路径

# 创建目标文件夹，并在其名称后添加"30_30"后缀
destination_folder_new = destination_folder + "_30_30"
os.makedirs(destination_folder_new, exist_ok=True)

# 遍历源文件夹中的所有文件
for filename in os.listdir(source_folder):
    if filename.endswith('.png'):  # 检查文件扩展名是否为.png
        # 构建源文件和目标文件的完整路径
        image_path = os.path.join(source_folder, filename)
        image = Image.open(image_path)

        # 压缩图像到30x30像素
        compressed_image = image.resize((30, 30))

        # 构建新的文件名
        new_filename = filename.rsplit('.', 1)[0] + '_30_30.' + filename.rsplit('.', 1)[1]
        new_image_path = os.path.join(destination_folder_new, new_filename)

        # 保存压缩后的图像
        compressed_image.save(new_image_path)
        print(f'压缩并保存了 {new_filename}')

print('所有.png文件已处理并压缩到30x30像素。')
